layui.extend({
    baseConfig : "/js/pages/baseConfig"
})
layui.use(['form','layer','laydate','table','laytpl','element','util','baseConfig','upload'],function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        upload = layui.upload,
        baseConfig = layui.baseConfig,
        table = layui.table;
    var util = layui.util;
    var tableIns = table.render({
        elem: '#list',
        url : '/qonto/list/',
        text: { none: "Aucun résultat"},
        cellMinWidth : 95,
        height : "full-125",
        id : "listTable",
        page: true, //开启分页
        limit : 20,
        limits : [20,50,70,100],
        cols : [[
            {field: 'emittedAt', title: "Date", align:"center", templet: function ( d) {
                return baseConfig.formatDate( d.emittedAt);
            }},
            {field: 'label', title: "Contrepartie", align:"center", templet : function( d){
                return "<div style=\"overflow:hidden;white-space:nowrap;text-overflow:ellipsis;\">" + d.label + "</div>";
            }},
            {field: '', title: "Justificatif", align:'center', templet : function( d){
                if( d.invoice){
                    if( d.invoiceStatus == "PASS"){
                        return "<span style='color: green'>Attaché</span>";
                    }else if( d.invoiceStatus == "REJECT"){
                        return "<span style='color: red'>Attaché</span>";
                    }else{
                        return "<span style='color: gray'>Attaché</span>";
                    }
                }else{
                    return "<span style=''>Non renseigné</span>";
                }
            }},
            {field: 'amount', title: "Montant", align:'center', templet : function( d){
                var profix = "";
                var color = "";
                if( d.side == "credit"){//转入
                    color = "green";
                }else if( d.side == "debit"){//转出
                }
                return "<span style='color:"+ color +"'>" + profix + parseFloat( d.amount).toFixed( 2) + " €" + "</span>";
            }},
            {title: 'État', align:"center", templet : function ( d) {
                    var str = "";
                    if( d.invoice) {
                        if (d.invoiceStatus == "PASS") {
                            str += "<a class=\"layui-btn layui-btn-xs\" lay-event=\"viewInvoice\">查看发票</a>";
                        } else {
                            if( baseConfig.checkPrivalege( baseConfig.INVOICE_REVIEW)){
                                if( d.invoice == "LOSE"){
                                    str += " <a class=\"layui-btn layui-btn-xs layui-btn-warm\" lay-event=\"reviewInvoice\">审核发票(发票遗失)</a>";
                                }else{
                                    str += " <a class=\"layui-btn layui-btn-xs layui-btn-warm\" lay-event=\"reviewInvoice\">审核发票</a>";
                                }
                            } else {
                                str += "<a class=\"layui-btn layui-btn-xs layui-btn-normal\" lay-event=\"uploadInvoice\">重新上传发票</a>";
                            }
                        }
                    }else {
                        str += "<a class=\"layui-btn layui-btn-xs layui-btn-normal\" lay-event=\"uploadInvoice\">上传发票</a>";
                    }
                    return str;
                }}

        ]],
        response : {
            statusCode: 200 //规定成功的状态码，默认：0
        },
        parseData : function( res){ //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.count, //数据条数
                "data": res.data.data //解析数据列表
            };
        }
    });

    //加载日期选择框
    laydate.render({
        elem: '#emitted_at_start',
        format: 'yyyy-MM-dd',
        trigger: 'click',
        lang: 'en',
        max : 0
    });
    laydate.render({
        elem: '#emitted_at_end',
        format: 'yyyy-MM-dd',
        trigger: 'click',
        lang: 'en',
        max : 0
    });
    //查询 账户总额信息
    $.get("/qonto/getAccountTotal",function( res){
        if( res.code == 200){
            var total = res.data;
            $("input[name=total_count]").val( total);
        }
    });

    //手动同步流水数据
    $("#sync_data_btn").click(function(){
        var index = layer.open({ type: 3});
        $.post("/qonto/syncData",{},function( res){
            if( res.code == 200){
                tableIns.reload();
                layer.close( index);
                top.layer.msg( "同步交易流水成功");
            }else{
                top.layer.close( index);
                top.layer.msg( "同步交易流水失败");
            }
        });
    });
    //上传excel文件
    upload.render({
        elem: '#import_excel_btn',
        url: '/file/upload?type=qontoImportExcel',
        method : "post",
        accept : "file",
        exts : "csv",
        done: function(res){
            if( res.code == 200){
                var excelPath = res.data.filePath;
                var index = layer.msg('导入中，请稍候....',{ icon: 16, time:false, shade:0.8});
                //调用excel解析接口
                $.post( "/qonto/importFromExcel",{
                    "filePath" : excelPath
                },function( res){
                    layer.close( index);
                    if( res.code == 200){
                        var repeatCount = res.data.repeatCount;
                        var successCount = res.data.successCount;
                        var errorDatas = res.data.errorDatas;

                        var msg = "导入成功,本次成功导入[" + successCount + "]条数据";
                        if( repeatCount != 0){
                            msg += "，出现条[" + repeatCount + "]重复导入的数据";
                        }
                        if( errorDatas && errorDatas.length != 0){
                            var errStrs = "";
                            for( var i = 0 ; i < errorDatas.length ; i++){
                                if( i != 0){
                                    errStrs += ",";
                                }
                                errStrs += errorDatas[i].rowNum;
                            }
                            msg += "，出现表格数据{" + errStrs + "}这几行因为格式错误导入失败的数据";
                        }
                        top.layer.alert( msg);
                        tableIns.reload();
                    }else{
                        top.layer.alert( res.msg ? res.msg : "导入失败");
                    }
                });
            }
        }
    });

    $("#import_excel_a").on("click",function(){
        //触发文件上传按钮的点击时间
        $("#import_excel_btn").triggerHandler( "click");
    });

    //搜索
    $(".search_btn").on("click",function(){
        var emitted_at_start = null;
        var emitted_at_end = null;
        //校验结束时间不能小于开始时间
        if( emitted_at_start && emitted_at_end){
            var startDate = new Date( emitted_at_start);
            var endDate = new Date( emitted_at_end);
            if( startDate.getTime() > endDate.getTime()){
                layer.msg( "交易结束时间必须大于交易开始时间");
                return;
            }
        }
        table.reload("listTable",{
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: { "emitted_at_start": emitted_at_start, "emitted_at_end": emitted_at_end}
        })
    });

    //获取浏览器最大高度，以防页面显示不完全
    var maxHeight = $(window).height();

    //打开上传发票页面
    function uploadInvoice( data, readonly){
        if( data.invoiceStatus == "PASS" && !readonly){
            top.layer.alert( "发票已经审核通过，不能再次上传");
            return;
        }
        var index = layui.layer.open({
            title : "发票信息",
            type : 2,
            area: [850 + 'px', ( maxHeight-10) + 'px'],
            shade: 0.4,
            btnAlign: 'r',
            id: "upload_invoice", //设定一个id，防止重复弹出
            content : "invoice.html",
            success : function(){
                var body = layui.layer.getChildFrame( 'body', index);
                if( data){
                    body.find( "input[name=id]").val( data.id).attr( "readonly", readonly);//标识是修改还是新增
                    if( data.invoice){
                        body.find( "input[name=invoice]").val( data.invoice).attr( "readonly", false);
                        body.find( "input[name=invoiceImg]").val( data.invoiceImg).attr( "readonly", false);
                        body.find( "#pdfImg").attr( "src", data.invoiceImg);
                    }
                    body.find( "input[name=dateDeDepense]").val( data.dateDeDepense).attr( "readonly", readonly);
                    body.find( "input[name=fournisseur]").val( data.fournisseur).attr( "readonly", readonly);
                    if( data.invoiceRate == "other"){
                        body.find( "#invoiceRateRadioThree").attr( "checked", "checked").attr( "readonly", true);
                    }else if( data.invoiceRate == "20%"){
                        body.find( "#invoiceRateRadioOne").attr( "checked", "checked").attr( "readonly", true);
                    }else{
                        body.find( "#invoiceRateRadioTwo").attr( "checked", "checked").attr( "readonly", true);
                    }
                    if( data.invoiceMoney){
                        body.find( "input[name=invoiceMoney]").val( data.invoiceMoney).attr( "readonly", false);
                    }else{
                        body.find( "input[name=invoiceMoney]").val( (parseFloat( data.montantTTC)/6).toFixed( 2)).attr( "readonly", readonly);
                    }
                    body.find( "input[name=montantTTC]").val( parseFloat( data.montantTTC).toFixed( 2)).attr( "readonly", readonly);
                    if( readonly){
                        body.find( ".invoiceDiv").attr("style","display:none;");
                        body.find( "#submitDiv").hide();
                    }
                    form.render();
                }
                setTimeout( function(){
                    layui.layer.tips('点击此处返回发票列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500);
            }
        });
    }

    //打开审核发票页面
    function reviewInvoice( data){
        if( data.invoiceStatus == "PASS"){
            top.layer.alert( "发票已经审核通过，不能再次审核");
            return;
        }
        var index = layui.layer.open({
            title : "审核发票",
            type : 2,
            area: [850 + 'px', (maxHeight - 10) + 'px'],
            shade: 0.4,
            btnAlign: 'r',
            id: "review_invoice", //设定一个id，防止重复弹出
            content : "invoiceReview.html",
            success : function(){
                var body = layui.layer.getChildFrame( 'body', index);
                body.find( "input[name=id]").val( data.id).attr( "readonly", true);//标识是修改还是新增
                if( data.invoice){
                    body.find( "input[name=invoice]").val( data.invoice).attr( "readonly", false);
                    body.find( "input[name=invoiceImg]").val( data.invoiceImg).attr( "readonly", false);
                    body.find( "#pdfImg").attr( "src", data.invoiceImg);
                }
                body.find( "input[name=dateDeDepense]").val( data.dateDeDepense).attr( "readonly", true);
                body.find( "input[name=fournisseur]").val( data.fournisseur).attr( "readonly", true);
                if( data.invoiceRate == "other"){
                    body.find( "#invoiceRateRadioThree").attr( "checked", "checked").attr( "readonly", true);
                }else if( data.invoiceRate == "20%"){
                    body.find( "#invoiceRateRadioOne").attr( "checked", "checked").attr( "readonly", true);
                }else{
                    body.find( "#invoiceRateRadioTwo").attr( "checked", "checked").attr( "readonly", true);
                }
                body.find( "input[name=montantTTC]").val( parseFloat( data.montantTTC).toFixed( 2)).attr( "readonly", true);
                body.find( "input[name=invoiceMoney]").val( (parseFloat( data.montantTTC)/6).toFixed( 2)).attr( "readonly", true);
                form.render();
                setTimeout( function(){
                    layui.layer.tips('点击此处返回发票列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500);
            }
        });
    }

    //列表操作
    table.on('tool(list)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'viewInvoice'){ //查看发票
            uploadInvoice( data, true);
        }else if(layEvent === 'uploadInvoice'){ //上传发票
            uploadInvoice( data, false);
        }else if(layEvent === 'reviewInvoice'){ //审核发票
            reviewInvoice( data);
        }
    });
});
